////<!--黑名单车辆信息-->
import api from '../../../fetch/api'

import { deepCopyObj } from '../../../assets/js/help.js'
export default {
    data() {
        var validateAvailTimeFromTo = (rule, value, callback) => {
            var self = this;
            if(self.showBlackTime=='CLOSE'){
                if (value == null || value == '' || value == ',') {
                    return callback(new Error('请选择黑名单生效期'));
                }        
            }
            callback();
        };
        var validateParkJson = (rule, value, callback) => {
            var self = this;
            if (!self.mouthTicketData.dataSave.parkJson.length) {
                return callback(new Error('请选择支持的停车场'));
            }
            for (var i = 0; i < self.mouthTicketData.dataSave.parkJson.length; i++) {
                var parkJsonItem = self.mouthTicketData.dataSave.parkJson[i];

                if (!parkJsonItem.parkVipTypeId) {
                    return callback(new Error('请选择停车场的VIP类型'));
                }
            }
            callback();
        };
        var validateMonthShow = (rule, value, callback) => {
            var self = this;
            if(self.showBlackTime=='OTHER'){
                if (!self.monthShow.length) {
                    return callback(new Error('请选择自然月'));
                }
            }
            callback();
        };
        return {
            dialogVisibleForEmergency: false, //是否显示告警设置框
            cardNoIn: false, //黑名单进场告警开关
            cardNoOut: false, //黑名单离场告警开关
            pos_cardNoIn: false, //黑名单进场告警开关-pos机
            pos_cardNoOut: false, //黑名单离场告警开关-pos机
            emergencySetupId: '', //告警设置id
            selectAllItemsStatus:'0',
            itemsNum:0,
            itemsKeyName:'',
            showBlackTime: 'CLOSE',//是否显示有效时间标志
            monthShow: [],  //显示选中的自然月
            naturalMonthData: {   //自然月日历数据
                year: '',
                month: [
                    ['一月', '二月', '三月', '四月'],
                    ['五月', '六月', '七月', '八月'],
                    ['九月', '十月', '十一月', '十二月'],
                ]
            },
            yearN: '',
            monthN: '',            
            alreadySelect: [],

            syncDetailModal: {
                theadsInfo: [
                  { index: 0, isShow: false, prop: 'parkName', text: '支持停车场', minWidth: 120 },
                  { index: 1, isShow: false, prop: 'customVipName', text: '绑定VIP类型', minWidth: 120 },
                  { index: 2, isShow: false, prop: 'sendTime', text: '同步时间', minWidth: 170 },
                  { index: 3, isShow: false, prop: 'sendStatus', text: '同步结果', minWidth: 120 },
                  { index: 4, isShow: false, prop: 'respDesc', text: '失败原因', minWidth: 120 },
                  { index: 5, isShow: false, prop: 'operate', text: '操作', minWidth: 120 },
                ],
                syncDetailList:[]
            },
            supportParkList: [],
            supportPark: {
                theadsInfo: [
                    { index: 0, isShow: false, prop: 'parkName', text: '停车场', minWidth: 120 },
                    { index: 1, isShow: false, prop: 'parkVipTypeStr', text: '绑定VIP类型', minWidth: 120 },
                    { index: 2, isShow: false, prop: 'sourceParkName', text: '添加黑名单车场', minWidth: 120 },
                ]
            },
            specialCarTypeConfigName:'',
            actionStatus:'add',
            specialCarTypeConfigList:[],
            mouthTicketData: {
                isShowSpecialCarType: false,
                isCreate: true,
                isAble: true,
                dataSave: {   //用于保存时发送到后台的数据
                    specialCarTypeConfigId:'',
                    id: '',
                    carLicenseNumber: '',
                    owner: '',
                    reason: '',
                    remark1: '',
                    remark2: '',
                    blacklistForeverFlag: '',
                    availTimeFromTo: '',
                    sourceParkuuid: '',
                    parkJson: [],   //每条记录都记录 停车场的ID和对应的VIP类型的关系
                }
            }, 
            entity: {
                specialCarTypeConfigId:'',
                id: null,
                carLicenseNumber: '',
                owner: '',
                reason: '',
                remark1: '',
                remark2: '',
                blacklistForeverFlag: '',
                parkList: [],
                availableParkCodeList: [],
                availTimeFromTo: '',
                sourceParkuuid: '',
            },
            tableData: {
                ParkNameList: [],//用于请求VIP类型的列表的车场name参数
                parkIdList: [],  //用于请求VIP类型的列表的车场ID参数
                parkVipTypeId: [],//当点击编辑按钮时  显示上一次保存的对应的VIP类型
                parkItems: [],  //通过停车场的ID请求到的停车场对应的VIP类型的列表
                ifSourcePark: [],
            },
            rules: {
                specialCarTypeConfigId: [{
                    required: true,
                    message: '特殊车辆类型不能为空',
                    trigger: 'change'
                }],
                carLicenseNumber: [
                    { required: true, message: '车牌号码不能为空', trigger: 'change' },
                    { max: 8, message: '最多8 个字符', trigger: 'change' }
                ],
                owner: [
                    { required: true, message: '车主姓名不能为空', trigger: 'change' },
                    { max: 10, message: '最多10 个字符', trigger: 'change' }
                ],
                reason: [
                    { required: true, message: '黑名单原因不能为空', trigger: 'change' },
                    { max: 100, message: '最多100 个字符', trigger: 'change' }
                ],
                remark1: [
                    { max: 100, message: '最多100 个字符', trigger: 'change' }
                ],
                remark2: [
                    { max: 100, message: '最多100 个字符', trigger: 'change' }
                ],
                blacklistForeverFlag: [
                    { required: true, message: '黑名单生效期选项不能为空', trigger: 'change' },
                ],
                availTimeFromTo: [
                    { validator: validateAvailTimeFromTo, trigger: 'change' }
                ],
                parkJson: [
                    { type: 'array', required: true, message: '支持停车场不能为空', trigger: 'change' },
                    { validator: validateParkJson, trigger: 'change' }
                ],
                monthShow: [
                    { validator: validateMonthShow, trigger: 'change' },
                ],

            },
            remarkChunkShow: false,
        }
    },
    watch: {
        'mouthTicketData.dataSave.parkJson': function (newMouthTicketData) {
            if (this.$refs.ticketForm) {
                this.$refs.ticketForm.validateField('parkJson');
            }
        }
    },
    created() {
        toBase64(this);
        function toBase64(vm) {
            $(document).on('change', "#traderSelling input", function () {
                var file = this.files[0];
                var reader = new FileReader();
                if (!/image\/\w+/.test(file.type)) {
                    vm.showToast('请确保文件为图像类型', 2);
                    $("#traderSelling input").val('');
                    return false;
                }
                vm.mouthTicketData.dataSave.sellingPicName = file.name;
                reader.readAsDataURL(file);
                reader.onload = function (e) {

                    var res = e.target.result.replace("data:image/png;base64,", "");
                    res = res.replace("data:image/jpg;base64,", "");
                    res = res.replace("data:image/jpeg;base64,", "");
                    vm.mouthTicketData.dataSave.sellingPic = res;
                };
            });
            $(document).on('change', "#traderSellout input", function () {
                var file = this.files[0];
                var reader = new FileReader();
                if (!/image\/\w+/.test(file.type)) {
                    vm.showToast('请确保文件为图像类型', 2);
                    $("#traderSellout input").val('');
                    return false;
                }
                vm.mouthTicketData.dataSave.selloutPicName = file.name;
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    var res = e.target.result.replace("data:image/png;base64,", "");
                    res = res.replace("data:image/jpg;base64,", "");
                    res = res.replace("data:image/jpeg;base64,", "");
                    vm.mouthTicketData.dataSave.selloutPic = res;
                };
            });
        };
        var self = this;
        self.yearN = this.yearNow();
        self.monthN = this.monthNow();
    },
    methods: {
        // 添加黑名单类型-弹框
        addSpecialCarType(){
            this.$refs.specialCarTypeCom.createConfig('添加黑名单类型',2)
        },
        // 查看黑名单类型
        checkVisitorType(rowData){
            let params = {}
            params.specialCarTypeConfigId = rowData && rowData.specialCarTypeConfigId ? rowData.specialCarTypeConfigId : this.mouthTicketData.dataSave.specialCarTypeConfigId
            if(!params.specialCarTypeConfigId){
                this.showToast('请先选择类型',0,1500);
                return;
            }
            this.$refs.specialCarTypeCom.checkSpecialCarType(params,2)
        },
        //打开告警设置框
        openEmergencySetup(){
            let self = this
            API.fetchGet('park/emergency/config/getBlacklist.do',{}).then(res=>{
                let data = res.data
                self.emergencySetupId = data.id
                self.cardNoIn = data.blacklistIn
                self.cardNoOut = data.blacklistOut
                self.pos_cardNoIn = data.lmBlacklistIn
                self.pos_cardNoOut = data.lmBlacklistOut
            },err=>{})
            this.dialogVisibleForEmergency = true
        },
        //保存告警设置
        saveEmergencySetup(){
            let self = this
            let params = {};
            params.id = self.emergencySetupId
            params.blacklistIn = self.cardNoIn==null ? false : self.cardNoIn
            params.blacklistOut = self.cardNoOut==null ? false : self.cardNoOut
            params.lmBlacklistIn = self.pos_cardNoIn==null ? false : self.pos_cardNoIn
            params.lmBlacklistOut = self.pos_cardNoOut==null ? false : self.pos_cardNoOut
            API.fetchPost('park/emergency/config/updateBlacklist.do',params).then(res=>{
            // console.log('res:',res)
            self.dialogVisibleForEmergency = false
            },err=>{})
        },
        getList() {
            let params = $.extend({}, this.searchParams, this.otherParams);
            this.getMonthTicketManageList(params);
        },
        getMonthTicketManageList(aparams) {
            let self = this,
                params = {
                    page: this.pageNumber,
                    rp: this.pageSize
                };
            params = $.extend({}, params, aparams);
            API.park.GetParkBlacklistData(params)
                .then(res => {
                    let data = res.data,
                        list = data.rows;
                    self.tbodysInfo = list;
                    self.total = data.total;
                }, err => { })
        },
        resetMouthData() {
            this.mouthTicketData.dataSave = {
                specialCarTypeConfigId: '',
                id: '',
                carLicenseNumber: '',
                owner: '',
                reason: '',
                remark1: '',
                remark2: '',
                blacklistForeverFlag: '',
                availTimeFromTo: '',
                sourceParkuuid: '',
                parkJson: [],
            };
            this.mouthTicketData.isCreate=true;
            this.tableData = {
                ParkNameList: [],
                parkIdList: [],
                parkVipTypeId: [],
                parkItems: [],
                ifSourcePark: [],
            };
            this.entity.parkList = [];
            this.showBlackTime = '';
            this.monthShow= [];
        },
        createTicket(type) {
            var self = this;
            self.naturalMonthData.year = self.yearNow();
            self.traderstatus = 'new';
            self.actionStatus = 'add';
            self.remarkChunkShow = false
            self.resetMouthData();
            self.getVisitorConfigList();         
            self.toOpenModal('createBlackModal', 1)
        },
        getVisitorConfigList(type){
            var self = this;
            API.fetchGet('/park/parkBlacklist/getBlacklistConfigList.do',{})
                .then(res => {
                    let data = res.data;
                    self.specialCarTypeConfigList = data;
                    if(type && type=='addNew'){
                        self.mouthTicketData.dataSave.specialCarTypeConfigId = self.specialCarTypeConfigList[0].id
                    }
                }, err => { })
        },
        supportParkShowModal(row) {
            this.supportParkList = []
            if(row.sysVersion<=2.3){
                this.supportParkList = row.parkList;
                this.toOpenModal('supportParkModal', 1);
            }else{
                this.initChannelTree(null, null, "ParkTree",row);
                this.toOpenModal('selectParkModal', 1);
            }
        },
        searchItems(treeName){
            var self = this;
            var treeObj = $.fn.zTree.getZTreeObj(treeName);
            var nodes = treeObj.getNodesByParamFuzzy("name", self.itemsKeyName, null);
            treeObj.cancelSelectedNode();
            nodes.forEach(function(node) {
                treeObj.selectNode(node,true,false);
            }, this);
        },
        selectAllItems(treeName){
            var self = this;
            var treeObj = $.fn.zTree.getZTreeObj(treeName);
            console.log(self.selectAllItemsStatus);
            if(self.selectAllItemsStatus=='0'){
                treeObj.checkAllNodes(true);
            }else{
                treeObj.checkAllNodes(false);
            }
            self.setItemNums(treeName);
        },
        setItemNums(treeName){
            var self = this;
            var treeObj = $.fn.zTree.getZTreeObj(treeName);
            var nodes = treeObj.getCheckedNodes(true);
            var itemsNum_ = 0;
            nodes.forEach(function(node) {
                if(!node.isParent && node.channelSeq){
                itemsNum_++;
                }
            }, this);
            self.itemsNum = itemsNum_;
        },
    initChannelTree(parkId, vipTypeId, treeName, rowParam) {
      var self = this;
      self.itemsNum = 0;
      var params,fetchUrl;
      if(rowParam){
        params = {
          id: rowParam.specialCarTypeConfigId
        };
        fetchUrl = "/park/parkVisitorlist/getConfigParkChannels.do";
      }
      api.fetchPost(fetchUrl, params).then(res => {
        if (res.data.length == 0) {
          return;
        }
        if (res.status == 1) {
          var data = res;
          if (data != null) {
            var nodes = res.data;
            var settings = {
              check: {
                enable: true,
                autoCheckTrigger: true,
                chkboxType: {
                  "Y": "ps",
                  "N": "ps"
                }
              },
              data: {
                key: {
                  checked: "checked",
                  chkDisabled: true,
                  children: "childrenList",
                }
              },
              view: {
                showIcon: false,
                showLine: false,
              },
              callback: {
                onCheck: function (event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj(treeName);
                  self.setItemNums(treeName);
                }
              }
            };
            $.fn.zTree.destroy(treeName);
            $.fn.zTree.init($("#ParkTree"), settings, []);
            var treeObj = $.fn.zTree.getZTreeObj(treeName);
            treeObj.addNodes(null, 0, nodes);
            //勾选父节点的操作
            var temp_checkNodes = treeObj.getCheckedNodes();
            temp_checkNodes.forEach(function(t) {
              if(!t.hasChildren){
                treeObj.checkNode(t,true,true);
              }
            }, this);
            treeObj.expandAll(true);
          } else {
            self.showToast('该停车场没有配置通道', 2, 3000);
          }
        } else {
          self.showToast(res.message, 2, 2000)
          return;
        }
      }, err => {})
    },       
       openSelectParkModal() {
            var _self = this;
            _self.toOpenModal('selectParkModal', 2);
            this.initParkTree("ParkTree");
        },
        initParkTree(treeId) {
            var _self = this;
            API.park.getParkTree({})
                .then(res => {
                    var data = res;
                    if (data != null) {
                        var nodes = data.data;
                        var jsonStr = JSON.stringify(nodes);
                        jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
                        nodes = JSON.parse(jsonStr);
                        var settings = {
                            check: {
                                enable: true,
                                chkStyle: "checkbox",
                                radioType: "all"
                            },
                            view: {
                                showIcon: false,
                                showLine: false,
                            },
                            callback: {
                                onClick: function (event, treeId, treeNode) {
                                    var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                                    treeObj.checkNode(treeNode, true, false);
                                    if (treeNode.isArea) {
                                        return;
                                    }
                                },
                            }
                        };
                        $.fn.zTree.destroy("ParkTree");
                        var treeObj = $.fn.zTree.init($("#ParkTree"), settings, nodes);
                        for (var i = 0; i < _self.entity.parkList.length; i++) {
                            var node = treeObj.getNodeByParam("value", _self.entity.parkList[i]);
                            if (node) {
                                if (node.getParentNode() && !node.getParentNode().open) {
                                    treeObj.expandNode(node.getParentNode(), true, true, true);
                                }
                                treeObj.checkNode(node, true, true);
                            }
                        }
                        treeObj.expandAll(true);

                    } else {
                        _self.showToast('暂时没有停车场可选', 2, 3000);
                    }
                }, err => { })

        },
        selectParkSure() {
            var self = this,
                nodes = [];
            var treeObj = $.fn.zTree.getZTreeObj("ParkTree");
            nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
            var parkList = new Array();
            // 初始化表格显示数据以及提交的表格参数
            self.tableData = {
                ParkNameList: [],
                parkIdList: [],
                parkVipTypeId: [],
                parkItems: [],
                ifSourcePark: [],
            };
            self.mouthTicketData.dataSave.parkJson = [];
            for (var i = 0; i < nodes.length; i++) {
                if (!nodes[i].isArea) {
                    parkList.push(nodes[i]);
                }
            }
            if (parkList.length <= 0) {
                self.showToast('请选择一个停车场', 0);
                return;
            }
            self.entity.parkList = [];
            for (var i = 0; i < parkList.length; i++) {
                self.entity.parkList.push(parkList[i].value);
                self.tableData.parkIdList.push(parkList[i].value);
                self.tableData.ParkNameList.push(parkList[i].name);
            }
            self.closed('selectParkModal', 2);
            self.getParkItems();
        },
        getParkItems() {       //循环请求每一个车场的VIP类型列表  如果是编辑的话  默认选中车场的VIP类型
            var self = this;
            var itemobj = {};
            var itemobjArr = [];
            var parkJson = {};    //表格每一行的的数据组成一个对象，，所有的行组成一个数组
            var parkJsonArr = []; //装parkJson对象的数组
            var param = {};
            var ParkNameList = self.tableData.ParkNameList;
            var parkIdList = self.tableData.parkIdList;
            for (var i = 0; i < parkIdList.length; i++) {
                itemobj = {};
                parkJson = {};
                param.parkId = parkIdList[i];
                $.ajax({
                    type: 'get',
                    url: '/mgr/monthTicketConfig/vipTypeList.do',
                    data: param,
                    cache: false,
                    dataType: 'json',
                    async: false,
                    success: function (data) {
                        if (data.data.length == 0) {
                            self.showToast('已过滤不存在VIP类型的停车场', 0, 2000);
                            return;
                        }
                        itemobj.ParkName = ParkNameList[i];
                        itemobj.parkId = parkIdList[i];
                        parkJson.parkId = parkIdList[i];
                        parkJson.parkVipTypeId = self.tableData.parkVipTypeId[i] || ''; // 编辑时默认选中VIP类型
                        parkJson.ifSourcePark = self.tableData.ifSourcePark[i];
                        parkJsonArr.push(parkJson)
                        itemobj.parkVipList = data.data;
                        itemobjArr.push(itemobj)
                    }
                });
            };
            self.mouthTicketData.dataSave.parkJson = parkJsonArr;
            self.tableData.parkItems = itemobjArr;
        },
        delectSelectParkItem(index, parkId) {
            var _this = this;
            _this.tableData.parkItems.splice(index, 1);
            _this.mouthTicketData.dataSave.parkJson.splice(index, 1);            
        },
        submitForm(formName) {
            var self = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    self.saveBlack();
                } else {
                    return false;
                }
            });
        },
        modifyBlack(black) {
            var self = this;
            self.entity.id = black.id;
            self.traderstatus = 'edit';
            self.actionStatus = 'edit';
            self.mouthTicketData.isCreate=false;
            self.editBlack(black.id, 'edit');
        },
        formatTime(value) {       //value为13位的时间戳
            function addzero(m) {
                return m < 10 ? '0' + m : m
            }
            var time = new Date(parseInt(value));
            var y = time.getFullYear();
            var m = time.getMonth() + 1;
            var d = time.getDate();
            var shi = time.getHours();
            var fen = time.getMinutes();
            var miao = time.getSeconds();
            if (value) {
                return y + '-' + addzero(m) + '-' + addzero(d) + ' ' + addzero(shi) + ':' + addzero(fen) + ':' + addzero(miao);
            }
        },
        editBlack(blackId, type) {
            var self = this;
            var params = {};
            self.mouthTicketData.isCreate = false;
            params.parkBlacklistId = blackId;
            self.resetMouthData();
            API.park.parkBlacklistDetail(params).then(res => {
                var data = res;
                // 转化时间戳
                var availTimeFrom = data.data.availTimeFrom;
                var availTimeTo = data.data.availTimeTo;
                self.mouthTicketData.dataSave.id = data.data.id;
                self.mouthTicketData.dataSave.carLicenseNumber = data.data.carLicenseNumber;
                self.mouthTicketData.dataSave.owner = data.data.owner;
                self.mouthTicketData.dataSave.reason = data.data.reason;
                self.mouthTicketData.dataSave.remark1 = data.data.remark1;
                self.mouthTicketData.dataSave.remark2 = data.data.remark2;
                self.mouthTicketData.dataSave.blacklistForeverFlag = data.data.blacklistForeverFlag;
                self.mouthTicketData.dataSave.sourceParkuuid = data.data.sourceParkuuid;

                self.specialCarTypeConfigName = data.data.specialCarTypeConfigName;
                self.mouthTicketData.dataSave.specialCarTypeConfigId = data.data.specialCarTypeConfigId;
                
                if (data.data.blacklistForeverFlag != 'OPEN'){
                    //自定义
                    if(data.data.timeperiodList.split('~').length==2){
                        self.showBlackTime = "CLOSE";
                        self.mouthTicketData.dataSave.blacklistForeverFlag="CLOSE";
                        self.mouthTicketData.dataSave.availTimeFromTo = [new Date(data.data.timeperiodList.split('~')[0]), new Date(data.data.timeperiodList.split('~')[1])];
                    }else{//自然月
                        self.showBlackTime = "OTHER";
                        self.mouthTicketData.dataSave.blacklistForeverFlag="OTHER";
                        for(var i=0;i<data.data.timeperiodList.split(',').length;i++){
                            var from=new Date(data.data.timeperiodList.split(',')[i].split('~')[0]);
                            var to=new Date(data.data.timeperiodList.split(',')[i].split('~')[1]);
                            var from_y=from.getFullYear();
                            var to_y=to.getFullYear();
                            var from_m=from.getMonth() + 1;
                            var to_m=to.getMonth() + 1;
                            if(i==0){
                                self.naturalMonthData.year=from_y;
                            }
                            if(from_y==to_y && from_m==to_m){
                                self.monthShow.push(from_y+'-'+self.digitalTrans(from_m));
                                
                            }else{
                                var monthNum=(to_y-from_y)*12-from_m+1+to_m;
                                var tmp=0;
                                for(var j=0;j<monthNum;j++){
                                    self.monthShow.push((from_y+tmp)+'-'+((from_m+j)%12==0?12:self.digitalTrans((from_m+j)%12)));
                                    if((from_m+j)%12==0){
                                        tmp++;
                                    }
                                }
                            }
                        }
                    }
                }

                if (data.data.blacklistForeverFlag == 'OPEN'){
                    self.showBlackTime = "OPEN";
                    self.naturalMonthData.year=self.yearNow();
                }
                
                self.entity.parkList = [];
                for (var i = 0; i < data.data.parkList.length; i++) {
                    self.tableData.ParkNameList.push(data.data.parkList[i].parkName)
                    self.entity.parkList.push(data.data.parkList[i].parkId);
                    self.tableData.parkIdList.push(data.data.parkList[i].parkId)
                    self.tableData.parkVipTypeId.push(data.data.parkList[i].parkVipTypeId)
                    self.tableData.ifSourcePark.push(data.data.parkList[i].ifSourcePark)
                };
                self.toOpenModal("createBlackModal", 1);
            }, err => { });
        },

        //小于10自然数前面补0，与标准日期适配
        digitalTrans(x) {
            return x<10?'0'+x:x;
        },

        saveBlack() {
            var self = this;
            var arr = [];
            var params = deepCopyObj(self.mouthTicketData.dataSave);
            if(self.showBlackTime=='CLOSE'){
                if (params['availTimeFromTo'] == '') {
                    self.showToast('请选择黑名单生效时间', 0);
                    return;
                }
                arr.push(self.mouthTicketData.dataSave.availTimeFromTo[0].Format('yyyy-MM-dd hh:mm:ss') + '~' + self.mouthTicketData.dataSave.availTimeFromTo[1].Format('yyyy-MM-dd hh:mm:ss'));
            }

            if (self.showBlackTime == 'OTHER') {
                var mouths = self.sortMonth(self.monthShow);
                for (var i = 0; i < mouths.length; i++) {
                    let m1 = mouths[i].split('~')[0];
                    let m2 = mouths[i].split('~')[1];
                    var pp1 = moment(m1, 'YYYY-MM').startOf('month').format('YYYY-MM-DD HH:mm:ss');
                    var pp2 = moment(m2, 'YYYY-MM').endOf('month').format('YYYY-MM-DD HH:mm:ss');
                    arr.push(pp1 + '~' + pp2)
                };
            } 
            if (self.showBlackTime == 'OPEN') {
                var dt = new Date();
                self.mouthTicketData.dataSave.availTimeFromTo=[new Date(),new Date("2100-01-01 00:00:00")];
                arr.push(self.mouthTicketData.dataSave.availTimeFromTo[0].Format('yyyy-MM-dd hh:mm:ss') + '~' + self.mouthTicketData.dataSave.availTimeFromTo[1].Format('yyyy-MM-dd hh:mm:ss'));
            }
            params.availTimeFromTo = arr.join(',');

            if (params.availTimeFromTo == '') {
                self.showToast('请选择有效日期', 0);
                return;
            }
            let url = self.traderstatus=='new' ? '/park/parkBlacklist/save.do' : '/park/parkBlacklist/edit.do';
            API.fetchPost(url,params).then(res => {
                var data = res;
                if (data.status == 1) {
                    if (self.traderstatus=='new') {
                        self.showToast('黑名单车辆创建成功', 1);
                    } else {
                        self.showToast('黑名单车辆修改成功', 1);
                    }
                    self.closed('createBlackModal');
                    self.getList();
                } else {
                    self.showToast(data.message, 2);
                }
            }, err => { });

        },
        delBlack(ticket) {
            var self = this;
            var params = {
                parkBlacklistId: ticket.id,
            };
            self.showDialog("确认删除该黑名单车辆?", '', function () {
                API.park.parkBlacklistDel(params).then(res => {
                    //start
                    var data = res;
                    self.showToast('删除黑名单车辆成功', 1);
                    self.getList();
                    //end
                }, err => { });
            })
        },//del ticket end
        //导出数据
        exportData() {
            let self = this;
            let theadsArr = []
            for(let i = 0; i<self.theadsInfo.length; i++){
            if(self.theadsInfo[i].checked){
                theadsArr.push(self.theadsInfo[i].prop)
            }
            }
            let params = {
                meterList: theadsArr.join(',')
            };
            params = $.extend({}, params, this.searchParams, this.otherParams);
            self.showDialog("确认导出该报表?", '', function () {
                self.toExportAsync('/park/parkBlacklist/exportParkBlacklist.do', params)
            })
            
        },//导出数据结束

        syncDetail(monthTicketBillDetailId,open){
            var self = this;
            self.syncDetailModal.syncDetailList = []
            let params = {
                parkBlacklistId:monthTicketBillDetailId
            };
            API.park.parkBlacklistFindSyncDetail(params)
            .then(res => {
              let data = res.data;
              self.syncDetailModal.syncDetailList = data;
              if(open){
                self.toOpenModal('syncDetailModal');
              }      
            }, err => {})
          },
          reSync(syncDetail){
            var self = this;
            let params = {
                id:syncDetail.id
            };
            API.park.parkBlacklistResync(params)
            .then(res => {
              self.syncDetail(syncDetail.parkBlacklistId);
              self.showToast('重新同步成功',false);
            }, err => {})
            
          },
          showBlack(event) {      
            if(event == "OPEN") {
              this.showBlackTime = 'OPEN';
            } 
            if(event == "OTHER"){
              this.showBlackTime = "OTHER"; 
            }
            if(event == "CLOSE"){
              this.showBlackTime = "CLOSE";        
            }
          },
          sortMonth(monthArr) {
            monthArr.sort(function (a, b) {
                var aArr = a.split("-");
                var bArr = b.split("-");
                //判断年份
                if (aArr[0] > bArr[0]) {
                    return 1;
                }
                if (aArr[0] < bArr[0]) {
                    return -1;
                }

                //年份相等判断月份
                if (parseInt(aArr[1]) > parseInt(bArr[1])) {
                    return 1;
                } else {
                    return -1;
                }
            });//排序完毕

            function isContinuous(a, b) {
                var aArr = a.split("-");
                var bArr = b.split("-");
                if (parseInt(aArr[0]) == parseInt(bArr[0]) && parseInt(aArr[1]) + 1 == parseInt(bArr[1])) {
                    return true;
                }
                if (parseInt(aArr[0]) + 1 == parseInt(bArr[0]) && parseInt(aArr[1]) == 12 && parseInt(bArr[1]) == 1) {
                    return true;
                }
                return false;
            }

            function merge(a, b) {
                return a + "~" + b;
            }

            var newMonthArray = [];
            for (var i = 0; i < monthArr.length; i++) {
                if (newMonthArray.length == 0) {
                    newMonthArray.push(monthArr[i] + "~" + monthArr[i]);
                    continue;
                }
                if (isContinuous(newMonthArray[newMonthArray.length - 1].split("~")[1], monthArr[i])) {
                    newMonthArray[newMonthArray.length - 1] = newMonthArray[newMonthArray.length - 1].split("~")[0] + "~" + monthArr[i];
                } else {
                    newMonthArray.push(monthArr[i] + "~" + monthArr[i]);
                }
            }
            return newMonthArray;
          },
          yearNow() {
            var dt = new Date();
            return dt.getFullYear();  //获取年(四位)   用于判断日历不能选择今天之前的月份
          },
          monthNow() {
            var dt = new Date();
            return dt.getMonth() + 1;  //获取月份   用于判断日历不能选择今天之前的月份
          },
          cut() {
            var yearNow = this.yearNow();
            if (this.naturalMonthData.year == yearNow) {
                return;
            } else {
                this.naturalMonthData.year--;
            }
          },
          add() {
            this.naturalMonthData.year++;
          },
          del(index) {
            this.monthShow.splice(index, 1)
          },
          getMonth(index, tt) {
            var yearNow = this.yearNow();
            var monthNow = this.monthNow();
            var month = index + 1 + (tt * 4) >= 10 ? index + 1 + (tt * 4) : "0" + (index + 1 + (tt * 4));
            if (this.naturalMonthData.year == yearNow) {
                if (month < monthNow) {
                    return;
                }
            }
            var date = this.naturalMonthData.year + '-' + month;
            if (this.monthShow.length == 0) {
                this.monthShow.push(date);
                return;
            } else {
                for (var i = 0; i < this.monthShow.length; i++) {
                    if (this.monthShow[i] == date) {
                        this.monthShow.splice(i,1)
                        return;
                    }
                }
                for (var i = 0; i < this.alreadySelect.length; i++) {
                    if (this.alreadySelect[i] == date) {
                        return;
                    }
                }
            }
            this.monthShow.push(date);
           },
    },
    filters: {
        sendStatus: function (val) {
            switch (val) {
                case 0:
                    return '未发送'
                case 1:
                    return '发送中'
                case 2:
                    return '同步成功'
                case 3:
                    return '同步失败'
                default:
                    break;
  
            }
        }
        
    },
}